from com.chq.panbaidu.GetBAIDUID import *
from com.chq.panbaidu.GetShareLink import *
import pymysql.cursors


def update_flag(flag, url):
    # 获取数据连接
    connection = pymysql.connect(host="127.0.0.1", user="root", password="root", db="common", charset="utf8mb4")
    cursor = connection.cursor()
    try:
        # 创建sql语句
        sql = "update `music_51ape` set `flag`=%s where `url`=%s"
        # 执行sql语句
        cursor.execute(sql, (flag, url))
        # 提交
        connection.commit()
    except Exception as e:
        # 错误回滚
        connection.rollback()
    finally:
        connection.close()


class main_app():
    getBID = GetBAIDUID()
    getShareLink = GetShareLink()

    def Works(self, url, inputPwd):
        self.getBID.getID()
        self.getShareLink.getShareLink(url, inputPwd)


if __name__ == '__main__':
    mainapp = main_app()
    connection = pymysql.connect(host="127.0.0.1", user="root", password="root", db="common", charset="utf8mb4")
    cursor = connection.cursor()
    try:
        # 创建sql语句
        sql = "SELECT `id`,`ape_url`,`flag`,`url`,`password` FROM `music_51ape`" \
              " WHERE `flag`<2 and `url` is not null order by id desc"
        # 执行sql语句
        cursor.execute(sql)
        # 获取所有记录列表
        results = cursor.fetchall()
        for row in results:
            print(row[3], row[4])
            try:
                mainapp.Works(row[3], row[4])
            except KeyError as ke:
                update_flag(9, row[3])

    finally:
        connection.close()
